<template>
	<div style="height: calc(100vh - 223px);" >
		<div style="padding: 5px;margin-bottom: 5px;display: flex;justify-content: flex-start;align-items: center;">
			<div >
				<el-button type="primary" :disabled="disabled" @click.stop="saveForm" :loading="loading">保存</el-button>
			</div>
			<el-divider direction="vertical" />
			<div>
				<el-button type="warning" :disabled="!formData.dsId" @click.stop="execute" :loading="loading">执行Sql</el-button>
			</div>
		</div>
		
		<div style="height: calc(100% - 51px);">
			<el-scrollbar height="100%">
				<div class="sql-pane">
					<div class="head">
						<span>Sql配置表单信息</span>
					</div>
					<div class="body">
						<ElForm ref="formRef" :model="formData" :rules="fieldRules" label-width="135px">
						  <ElFormItem label="数据源" prop="dsId">
							<ElSelect v-model="formData.dsId" placeholder="请选择Sql数据源">
							  <ElOption 
								v-for="ds in dbConfigOptions" 
								:key="ds.id" 
								:label="ds.name" 
								:value="ds.id" 
							  />
							</ElSelect>
						  </ElFormItem>
						  <ElFormItem label="Sql语句" prop="sqlContent" >
							<ElInput v-model="formData.sqlContent" type="textarea" :rows="10" :disabled="disabled"/>
						  </ElFormItem>
						</ElForm>
					</div>
				</div>
				
				<div class="sql-pane" v-if="resultVisible" style="margin-top: 5px;">
					<div class="head">
						<span>Sql执行结果</span>
					</div>
					<div class="body" style="padding-top: 0px;">
						<ArtTable
						  ref="tableRef"
						  row-key="id"
						  :loading="loading"
						  :data="tableData"
						  :pagination="false"
						  :marginTop="10"
						>
						  <template #default>
							<ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
						  </template>
						</ArtTable>
					</div>
				</div>
			</el-scrollbar>
		</div>
	</div>
</template>

<script setup lang="ts">
	import { h, ref, reactive, onMounted, nextTick } from 'vue'
	import { ElDialog, FormInstance, ElTag } from 'element-plus'
	import { ElMessageBox, ElMessage } from 'element-plus'
	import type { FormRules } from 'element-plus'
	import { useCheckedColumns } from '@/composables/useCheckedColumns'
	import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
	import { DataSourceService } from '@/api/sys/dataSourceApi'
	import { SearchChangeParams, SearchFormItem } from '@/types'
	import { useCommon } from '@/composables/useCommon'
	import { useWindowSize } from '@vueuse/core'
	import { RuleService } from '@/api/data-rule/ruleApi'
	import { DbConfigService } from '@/api/data-rule/dbApi'
	import { watch } from 'vue-demi'
	const emits = defineEmits(['refresh-tree'])
  const rule=ref<any>();
  const props=defineProps({
  	data: {
  		type: Object,
  		default: () => {}
  	},
  })
  const { containerMinHeight } = useCommon()
  const { width } = useWindowSize()
  defineOptions({ name: 'FolderForm' })
  
  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const disabled = ref(true)
  
  const resultVisible=ref<boolean>(false);
  
  //表单字段
  const formData = reactive({
    id: '',
    dsId: '',
    sqlContent: '',
  })
  
  // 验证规则
  const fieldRules = reactive<FormRules>({
    dsId: [
      { required: true, message: '请选择数据源', trigger: 'blur' }
    ],
    sqlContent: [
      { required: true, message: '请输入sql内容', trigger: 'change' }
    ],
  })
  
  const editRow=(oprType:string,row?:any)=>{
	  formData.id=row?.id || '';
	  formData.dsId=row?.dsId || '';
	  formData.sqlContent=row?.sqlContent || ''
	  disabled.value=false;
  }
  
  const getRow= async (id:string)=>{
	  const data = await RuleService.getSql(id);
	  editRow(data?'add':'edit',data);
  }
  
  const dbConfigOptions=ref<any>([]);
  const getDbConfigOptions= async ()=>{
	  dbConfigOptions.value= await DbConfigService.getOptions({query:{}});
  }
  
  const saveForm = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
			loading.value = true
			formData.id=rule.value.id
  			const data = await RuleService.saveSql(formData);
  			formData.id=data.id;
			emits('refresh-tree', formData)
  			ElMessage.success(`成功`)
        } catch {
  			ElMessage.error(`失败`)
        }finally{
			loading.value = false
		}
      }
    })
  }
  
  const tableData = ref<any[]>([])
  const { columns,resetColumns } = useCheckedColumns(() => [
  ]);
  const execute= async ()=>{
	  try {
	    await ElMessageBox.confirm('确定要执行Sql吗？', '提示', {
	      confirmButtonText: '确定',
	      cancelButtonText: '取消',
	      type: 'warning'
	    })
	  	loading.value = true
	  	try {
			resetColumns();
			resultVisible.value=true;
	  		const {tableMetas,records} =await RuleService.executeSql(rule.value.id);
			
			//console.log(tableMetas);
			//console.log(records);
			const columnMetas=tableMetas[0].columnMetas
			for(var column of columnMetas){
				columns.value.push({
					prop: column.name, 
					label: column.remarks
				})
			}
			tableData.value=[];
			tableData.value.push(records[0].columns)
	  		ElMessage.success('成功')
	  	} catch {
	  		ElMessage.error(`失败`)
	  	}finally{
	  		loading.value = false
	  	}
	  } catch (error) {
	    if (error !== 'cancel') {
	      ElMessage.error('失败')
	    }
	  }
  }
  
  watch(props,() => {
  		rule.value=props.data
		if(rule.value){
			getRow(rule.value.id);
			getDbConfigOptions();
		}
  	},
      { immediate: true, deep: true },
  )
  onMounted(() => {
  })
</script>

<style lang="scss" scoped>
	.sql-pane{
		border: 1px solid var(--art-card-border);
		.head{
			height: 2.1875rem;
			border-bottom: 1px solid var(--art-card-border);
			display: flex;display: flex;
			justify-content: flex-start;
			align-items: center;
			padding-left: 0.5rem;
		}
		.body{
			padding: 0.5rem;
		}
		
	}
</style>